package com.example.futureai.utils;

import cn.hutool.core.util.StrUtil;
import com.example.futureai.constants.RedisConst;
import com.example.futureai.service.RedisService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Map;
import java.util.UUID;

/**
 * @ClassName: TokenUtil
 * @Description:
 * @Author: YourName
 * @Date: 2025/2/27
 */
public class TokenUtil {
    public static String getCurrentUserId() {
        String currentUserId = "";
        RedisService redisService = ApplicationContextHolder.getBean(RedisService.class);
        currentUserId = redisService.get(String.format("%s%s", RedisConst.USER_TOKEN, getCurrentToken()));
        if(StrUtil.isBlank(currentUserId)){
            throw new RuntimeException("获取currentUserId失败！！！");
        }
        return currentUserId;
    }

    public static String getToken(Map<String, String> map) {
        RedisService redisService = ApplicationContextHolder.getBean(RedisService.class);
        //生产一个字符串
        String token = UUID.randomUUID().toString().replace("-", "");
        redisService.setObject(String.format("%s%s", RedisConst.USER_TOKEN, token), map.get("username"), 86400000);
        return token;
    }

    public static boolean validToken(String token) {
        RedisService redisService = ApplicationContextHolder.getBean(RedisService.class);
        String key = String.format("%s%s", RedisConst.USER_TOKEN, token);
        //校验token
        return redisService.hasKey(key);
    }

    public static String getCurrentToken() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        String token = request.getHeader("Authorization");
        if(StrUtil.isBlank(token)){
            //从参数中获取token
            token = request.getParameter("token");
        }
        return token;
    }
}
